/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-12-8 14:13:26
 ******************************************************************************/
package cn.com.xy.sms.sdk.util;

import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import cn.com.xy.sms.sdk.Iservice.IActionService;
import cn.com.xy.sms.sdk.action.AbsSdkDoAction;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;

public class LocalActionImpl implements IActionService {

    static IActionService localAction = new LocalActionImpl();

    /**
     * 依据包名和应用自定义的URL参数 打开应用指定界面。
     * 
     * @param ctx
     *            上下文
     * @param appPackageName
     *            包名
     * @param url
     *            应用指定界面的URL 如果为空，则表示打开应用首页。
     * @param jsonParams
     *            扩展的JSON字符串
     * @return true|false 成功或失败
     * @throws Exception
     */
    public static boolean startAppActionViewByURL(Context ctx, String appPackageName, String url, JSONObject jsonParams) throws Exception {

        try {
        	if(!ZFButil.isInstallPackageName(ctx, appPackageName)) return false;
        	
            IActionService actionService = DexUtil.getActionInterfaceImpl(false);
            if (actionService != null) {
                return actionService.startAppActionViewURL(ctx, appPackageName, url, jsonParams);
            } else {
                return localAction.startAppActionViewURL(ctx, appPackageName, url, jsonParams);
            }
        	
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "LocalActionImpl startAppActionViewByURL ", e);
        }
        return false;
    }

    /**
     * 执行动作
     * 
     * @param ctx
     * @param actionType
     * @param jsonParams
     * @return
     */
    public static boolean doActionOnImpl(Context ctx, String actionType, JSONObject jsonParams) {
        try {
            IActionService actionService = DexUtil.getActionInterfaceImpl(false);
            if (actionService != null) {
                return actionService.doAction(ctx, actionType, jsonParams);
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            LogManager.e(Constant.TAG, "doActionOnImpl: ", e);

        }
        return false;
    }

    @Override
    public boolean startAppActionViewURL(Context ctx, String appPackageName,
            String url, JSONObject jsonParams) throws Exception {
        try {
            if (ctx == null || StringUtils.isNull(appPackageName)
                    || jsonParams == null) {
                return false;
            }

            String appViewUrl = jsonParams.optString("viewUrl");
            String className = jsonParams.optString("className");
            JSONArray flags = jsonParams.optJSONArray("flags");
            String actionName = jsonParams.optString("actionName");
            JSONObject extras = jsonParams.optJSONObject("extras");
            String type = jsonParams.optString("type");
            Intent intent = null;

            // 生成intent，两种方式
            if (!StringUtils.isNull(appViewUrl)
                    || !StringUtils.isNull(actionName)|| !StringUtils.isNull(type)) {
                intent = new Intent();

                if (StringUtils.isNull(actionName)) {
                    actionName = Intent.ACTION_VIEW;
                }
                // 设置data
                if (!StringUtils.isNull(appViewUrl)) {
                    intent.setData(Uri.parse(appViewUrl));
                } 
                
                if(!StringUtils.isNull(type)){
                    intent.setType(type);
                }
                
                // 设置actionName
                intent.setAction(actionName);
            } else {
                if (!StringUtils.isNull(appPackageName)) {
                    intent = ctx.getPackageManager().getLaunchIntentForPackage(
                            appPackageName);
                }
            }

            if (intent == null){
                return false;
            }
            
            // 设置componetName
            if (!StringUtils.isNull(appPackageName)
                    && !StringUtils.isNull(className)) {
                ComponentName componetName = new ComponentName(appPackageName,
                        className);
                intent.setComponent(componetName);
            }

            // 设置flags
            if (flags != null && flags.length() > 0) {
                for (int i = 0; i < flags.length(); i++) {
                    intent.addFlags(flags.getInt(i));
                }
            }

            // 设置extras
            if (extras != null && extras.length() > 0) {
                Iterator<?> it = extras.keys();
                String key = "";
                while (it.hasNext()) {// 遍历JSONObject
                    key = (String) it.next().toString();
                    if (!TextUtils.isEmpty(key)) {
                        Object obj = (Object) extras.get(key);
                        if (obj instanceof String) {
                            intent.putExtra(key, (String) obj);
                        } else if (obj instanceof Boolean) {
                            intent.putExtra(key, (Boolean) obj);
                        } else if (obj instanceof Integer) {
                            intent.putExtra(key, (Integer) obj);
                        }

                    }
                }
            }

            ctx.startActivity(intent);

            return true;
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG,
                    "startAppActionViewURL: ", e);

        }
        return false;
    }

    @Override
    public boolean doAction(Context ctx, String actionType, JSONObject jsonParams) throws Throwable {
        // TODO Auto-generated method stub
        return false;
    }

}
